package com.zmn.oms.admin.controller.order;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import cn.hutool.core.util.IdUtil;
import com.github.ltsopensource.core.json.JSON;
import com.google.common.collect.Lists;
import com.zmn.anole.dubbo.interfaces.AnoleRemoteService;
import com.zmn.base.channel.common.dro.ChannelDRO;
import com.zmn.base.channel.common.enums.ChannelAccessModeEnum;
import com.zmn.base.common.data.common.constant.TagConsts;
import com.zmn.base.common.data.common.dro.area.AreaDRO;
import com.zmn.base.common.data.common.dro.brand.BrandDRO;
import com.zmn.base.common.data.common.dro.tags.TagsDRO;
import com.zmn.base.common.data.dubbo.interfaces.brand.BrandListRemoteService;
import com.zmn.base.price.common.dto.item.ItemDRO;
import com.zmn.base.price.common.dto.item.ItemPriceQuery;
import com.zmn.base.price.dubbo.interfaces.calculate.ItemPriceRemoteService;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.ccc.common.model.EncryptDataDRO;
import com.zmn.ccc.dubbo.interfaces.popup.PopupListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GateTypeConsts;
import com.zmn.mos.common.dio.order.add.NormalOrderAddDIO;
import com.zmn.mos.common.dio.order.add.OrderAddDIO;
import com.zmn.mos.common.dio.order.add.nest.*;
import com.zmn.mos.common.dio.order.add.shop.ExternalShopDIO;
import com.zmn.mos.common.dro.order.OrderAddDRO;
import com.zmn.mos.common.dro.order.OrderDetailDRO;
import com.zmn.mos.common.dro.order.OrderProductDetailDRO;
import com.zmn.mos.dubbo.interfaces.order.NormalOrderRemoteService;
import com.zmn.mos.dubbo.interfaces.order.OrderListRemoteService;
import com.zmn.mos.dubbo.interfaces.order.OrderModifyRemoteService;
import com.zmn.oms.admin.controller.OmsBaseController;
import com.zmn.oms.business.interfaces.base.BaseCodeService;
import com.zmn.oms.business.interfaces.purpose.OrderPurposeBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderDutyConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.MobileUtil;
import com.zmn.oms.common.vo.KVDict;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.dto.common.ChannelListQuery;
import com.zmn.oms.model.dto.order.zmn.NewZsNormalNewOrderDTO;
import com.zmn.oms.model.dto.order.zmn.ZsNormalNewOrderDTO;
import com.zmn.oms.model.dto.order.zmn.ZsNormalReworkOrderDTO;
import com.zmn.oms.model.dto.product.NewOrderAdvanceQuoteDTO;
import com.zmn.oms.model.dto.product.NewOrderProductDTO;
import com.zmn.oms.model.dto.product.OrderProductDTO;
import com.zmn.oms.model.dto.product.ProductQueryDTO;
import com.zmn.oms.model.dto.work.modify.amount.ZsUpdateChannelPrepayAmountDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.purpose.OrderPurpose;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.order.AddOrderVO;
import com.zmn.oms.model.vo.order.OrderAddressVO;
import com.zmn.oms.model.vo.order.OrderCallAddVO;
import com.zmn.oms.model.vo.order.RealPhoneVO;
import com.zmn.oms.model.vo.work.ZsNormalUpdateOrderVO;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.clue.OrderClueBService;
import com.zmn.oms.zmn.business.interfaces.order.ZsOrderBService;
import com.zmn.oms.zmn.normal.business.interfaces.work.masterwork.ZsNormalMasterWorkBService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

/**
 * 类描述：
 *
 * @author liuying
 * @date 2018/11/21 15:36
 */
@Controller
@RequestMapping("/order/normal")
public class OrderNormalController extends OmsBaseController {

    @Autowired
    private OrderPurposeBService orderPurposeBService;
    @DubboReference(version = com.zmn.mos.dubbo.utils.DubboConsts.INTERFACE_VERSION, timeout = 10000, check = false)
    private OrderModifyRemoteService orderModifyRemoteService;
    @DubboReference(version = com.zmn.mos.dubbo.utils.DubboConsts.INTERFACE_VERSION, timeout = 10000, check = false)
    private NormalOrderRemoteService normalOrderRemoteService;
    @DubboReference(version = com.zmn.mos.dubbo.utils.DubboConsts.INTERFACE_VERSION, timeout = 10000, check = false)
    private OrderListRemoteService orderListRemoteService;
    @DubboReference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private BrandListRemoteService brandListRemoteService;
    @DubboReference(version = AnoleRemoteService.VERSION, check = false)
    private AnoleRemoteService anoleRemoteService;
    @DubboReference(version = com.zmn.ccc.dubbo.interfaces.DubboConsts.INTERFACE_VERSION, check = false)
    private PopupListRemoteService popupListRemoteService;
    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private ItemPriceRemoteService itemPriceRemoteService;

    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private ZsOrderBService zsOrderBService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ZsNormalMasterWorkBService zsNormalMasterWorkBService;
    @Autowired
    private BaseCodeService baseCodeService;

    @Resource
    private OrderClueBService orderClueBService;

    /**
     * 下单限制文案
     */
    public static final String ADD_LIMIT_NOTICE = "此用户24小时内取消了该需求订单：用户此需求平台暂时无法服务。请再次确定用户真实需求！";


    @NacosValue(value = "${advance.special.faultphenId:0}", autoRefreshed = true)
    private Integer specialFaultPhenId;

    /**
     * 新增订单
     *
     * @return
     */
    @RequestMapping(value = "add")
    public ModelAndView add() {
        return createNormalOrderModelAndView("order/mosOrderAdd", GlobalConsts.PLAT_MARK_ZMN);
    }

    /**
     * 购物车-新增订单
     *
     * @return
     */
    @RequestMapping(value = "/mos/add")
    public ModelAndView mosOrderAdd() {
        return createNormalOrderModelAndView("order/mosOrderAdd", GlobalConsts.PLAT_MARK_ZMN);
    }

    /**
     * 新增言而有信普通订单
     *
     * @return
     */
    @RequestMapping(value = "yeyx/add")
    public ModelAndView addYeyxOrder() {
        return createNormalOrderModelAndView("order/mosOrderAdd", GlobalConsts.PLAT_MARK_YEYX);
    }

    /**
     * 新增saas普通订单
     *
     * @return
     */
    @RequestMapping(value = "saas/add")
    public ModelAndView addSaasOrder() {
        return createNormalOrderModelAndView("order/add", GlobalConsts.PLAT_MARK_SAAS);
    }

    /**
     * 新增川南环保普通订单
     *
     * @return
     */
    @RequestMapping(value = "cnhb/add")
    public ModelAndView addCnhbOrder() {
        return createNormalOrderModelAndView("order/mosOrderAdd", GlobalConsts.PLAT_MARK_CNHB);
    }

    /**
     * 啄木鸟-快捷录单
     *
     * @return
     */
    @RequestMapping(value = "simpleAdd")
    public ModelAndView simpleAdd() {

        ModelAndView modelAndView = createNormalOrderModelAndView("order/simpleAdd", null, true,
                ChannelAccessModeEnum.CHANNEL_ACCESS_MODE_NETWORK, true);

        // 来源渠道，所有平台&启用状态&非厂商渠道
        ChannelListQuery channelListQuery = ChannelListQuery.builder()
                .excludeDisabled(true)
                .factoryChannel(false).build();
        modelAndView.addObject("sourceChannelList", super.getChannelList(channelListQuery));

        return modelAndView;
    }

    /**
     * 言而有信-快捷录单
     *
     * @return
     */
    @RequestMapping(value = "yeyx/simpleAdd")
    public ModelAndView simpleYeyxAdd() {
        return createNormalOrderModelAndView("order/simpleAdd", GlobalConsts.PLAT_MARK_YEYX, true,
                ChannelAccessModeEnum.CHANNEL_ACCESS_MODE_NETWORK, true);
    }

    /**
     * SAAS-快捷录单
     *
     * @return
     */
    @RequestMapping(value = "saas/simpleAdd")
    public ModelAndView simpleSaasAdd() {
        return createNormalOrderModelAndView("order/simpleAdd", GlobalConsts.PLAT_MARK_SAAS, true,
                ChannelAccessModeEnum.CHANNEL_ACCESS_MODE_NETWORK, true);
    }

    /**
     * 川南环保-快捷录单
     *
     * @return
     */
    @RequestMapping(value = "cnhb/simpleAdd")
    public ModelAndView simpleCnhbAdd() {
        return createNormalOrderModelAndView("order/simpleAdd", GlobalConsts.PLAT_MARK_CNHB, true,
                ChannelAccessModeEnum.CHANNEL_ACCESS_MODE_NETWORK, true);
    }

    /**
     * 意向单下订单
     *
     * @return
     */
    @RequestMapping(value = "purposeAdd")
    public ModelAndView purposeAdd(@NotEmpty Integer orderPurposeId) {
        ModelAndView mv = createNormalOrderModelAndView("order/add", GlobalConsts.PLAT_MARK_ZMN, true,
                ChannelAccessModeEnum.CHANNEL_ACCESS_MODE_NETWORK, true);
        OrderPurpose orderPurpose = orderPurposeBService.findOrderPurposeByKey(orderPurposeId);
        ZsNormalUpdateOrderVO zsNormalUpdateOrderVO = BeanMapper.map(orderPurpose, ZsNormalUpdateOrderVO.class);
        zsNormalUpdateOrderVO.setPlat(GlobalConsts.PLAT_MARK_ZMN);
        zsNormalUpdateOrderVO.setPlatWork(GlobalConsts.PLAT_MARK_ZMN);
        mv.addObject("orderInfo", zsNormalUpdateOrderVO);
        return mv;
    }

    /**
     * 呼叫录单
     * http://local-oms.xiujiadian.com:10213/order/normal/callAdd.action?isRealPhone=2&callRecordId=10979215&callType=1&channelId=10120&servCategId=1002&telephone=16666666668&telephone2=15888888888&telephone3=15888888899&userName=%E5%B0%8F%E6%98%8E&productId=10770&number=2&brandId=1006&faultRemark=%E6%95%85%E9%9A%9C&provinceId=110000&cityId=110100&street=%E4%B8%AD%E5%85%B3%E6%9D%91768%E5%88%9B%E6%84%8F%E4%BA%A7%E4%B8%9A%E5%9B%AD&longitude=116.357383&latitude=40.014832&address=708%E5%AE%A4&dutyTime=2019-06-24%2017:30:00&remark=%E6%B5%8B%E8%AF%95&countyId=110108
     * http://test2-oms.xiujiadian.com/order/normal/callAdd.action?callType=1&callRecordId=10979215&channelId=1476&servCategId=1001&telephone=15888888889&telephone2=15888888888&telephone3=15888888899&userName=%E5%B0%8F%E6%98%8E&productId=10834&number=2&brandId=1006&faultRemark=%E6%95%85%E9%9A%9C&cityId=110100&street=%E4%B8%AD%E5%85%B3%E6%9D%91768%E5%88%9B%E6%84%8F%E4%BA%A7%E4%B8%9A%E5%9B%AD&longitude=116.357383&latitude=40.014832&address=708%E5%AE%A4&dutyTime=2019-06-24%2017:30:00&remark=%E6%B5%8B%E8%AF%95&countyId=110108
     * @return
     */
    @RequestMapping(value = "callAdd")
    public ModelAndView callAdd(OrderCallAddVO callAddVO) {
        String requestId = UUID.randomUUID().toString().replaceAll("-", "");
        logger.info("#callAdd requestId={} 入参{} ", requestId, callAddVO);

        // plat 为渠道对应的plat
        if (Objects.nonNull(callAddVO.getChannelId())) {
            ResponseDTO<ChannelDRO> channelDROResponseDTO = channelListRemoteService.getByChannelId(callAddVO.getChannelId());
            if (Objects.nonNull(channelDROResponseDTO.getData())) {
                callAddVO.setPlat(channelDROResponseDTO.getData().getPlat());
            }
        }

        // - 呼出Top，根据呼叫部门相应加载：渠道+城市+产品，以及下单后的下单平台
        // - 品控部、呼叫中心、订单管理部，对应：啄木鸟平台
        // - 网点管理部、客服部，对应：言而有信平台
        if (Objects.isNull(callAddVO.getPlat()) && Objects.equals(callAddVO.getCallType(), 2)) {
            callAddVO.setPlat(super.getCurrentStaff().getPlat());
        }

        callAddVO.setPlat(Optional.ofNullable(callAddVO.getPlat()).orElse(GlobalConsts.PLAT_MARK_ZMN));
        ModelAndView mv = createNormalOrderModelAndView("order/callAdd",
                callAddVO.getPlat(),
                true,
                ChannelAccessModeEnum.CHANNEL_ACCESS_MODE_TELEPHONE_TRAFFIC, false);

        OrderAddressVO orderAddressVO = BeanMapper.map(callAddVO, OrderAddressVO.class);

        // 呼入不隐藏号码，呼出隐藏
        ZsNormalUpdateOrderVO orderInfo = (ZsNormalUpdateOrderVO)mv.getModel().get("orderInfo");
        orderInfo.setTelephone(StringUtils.trim(callAddVO.getTelephone()));
        orderInfo.setHideTelephone(MobileUtil.formatHideTel(orderInfo.getTelephone()));
        orderInfo.setTelephone2(StringUtils.trim(callAddVO.getTelephone2()));
        orderInfo.setHideTelephone2(MobileUtil.formatHideTel(orderInfo.getTelephone2()));
        orderInfo.setTelephone3(StringUtils.trim(callAddVO.getTelephone3()));
        orderInfo.setHideTelephone3(MobileUtil.formatHideTel(orderInfo.getTelephone3()));

        // 其他信息
        orderInfo.setGender(callAddVO.getGender());
        orderInfo.setUserName(callAddVO.getUserName());
        orderInfo.setAddress(callAddVO.getAddress());
        mv.addObject("orderInfo", orderInfo);

        if (callAddVO.getCityId() != null) {
            orderAddressVO = BeanMapper.map(callAddVO, OrderAddressVO.class);

            if (Objects.isNull(callAddVO.getProvinceId())) {
                ResponseDTO<AreaDRO> areaDROResponseDTO = areaListRemoteService.getById(callAddVO.getCityId());
                if (Objects.nonNull(areaDROResponseDTO.getData())) {
                    orderAddressVO.setProvinceId(areaDROResponseDTO.getData().getParentId());
                }
            }
        }

        if (StringUtils.isNotBlank(callAddVO.getCityName())) {
            logger.info("#callAdd 获取城市信息 入参{} ", callAddVO.getCityName());
            ResponseDTO<List<AreaDRO>> cityResponseDTO = areaListRemoteService.getAreaByName(callAddVO.getCityName());
            logger.info("#callAdd 获取城市信息 出参{} ", JSON.toJSONString(cityResponseDTO));
            if (cityResponseDTO.isSuccess() && CollectionUtil.isNotNullOrEmpty(cityResponseDTO.getData())) {
                Optional<AreaDRO> optional = cityResponseDTO.getData().stream()
                        .filter(areaDRO -> Objects.equals(areaDRO.getName(), callAddVO.getCityName()) && Objects.equals(areaDRO.getLevel(), 3))
                        .findFirst();
                if (optional.isPresent()) {
                    orderAddressVO = BeanMapper.map(callAddVO, OrderAddressVO.class);
                    orderAddressVO.setCityId(optional.get().getAreaId());
                    orderAddressVO.setProvinceId(optional.get().getParentId());
                }
            }
        }

        // 产品
        if (orderAddressVO.getCityId() != null && callAddVO.getChannelId() != null) {
            ProductQueryDTO queryDTO = ProductQueryDTO.builder().plat(callAddVO.getPlat()).bizType(orderInfo.getBizType())
                    .servCategId(callAddVO.getServCategId()).showType(BaseProductConsts.EC_SHOW_TYPE)
                    .isIncludeDisabled(false).cityId(orderAddressVO.getCityId())
                    .channelId(callAddVO.getChannelId()).build();
            List<KVDict> servProductList = super.getServProductList(queryDTO);
            mv.addObject("servProductList", servProductList);

            logger.info("#callAdd requestId={} 产品列表：{} ", requestId, JSON.toJSONString(servProductList));
        }

        // 判断带入联系人电话是否为手机
        callAddVO.setTelephoneReadonly(StringUtil.isMobile(callAddVO.getTelephone()));

        // 设置渠道不可变更
        Object channelListObj = mv.getModel().get("channelList");
        if (Objects.nonNull(channelListObj) && Objects.nonNull(callAddVO.getChannelId())) {
            List<KVDict> channelList = (List<KVDict>) channelListObj;
            callAddVO.setChannelReadonly(channelList.stream().filter(item->Objects.equals(item.getValue(), callAddVO.getChannelId())).findAny().isPresent());
        }

        mv.addObject("orderAddressVO", orderAddressVO);
        mv.addObject("callAddVO", callAddVO);
        mv.addObject("requestId", requestId);

        return mv;
    }

    /**
     * 快捷下单，新增普通单
     *
     * @return
     */
    @RequestMapping(value = "simpleSave", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO saveSimpleOrder(@RequestBody @Valid NewZsNormalNewOrderDTO order) {

        // 快捷下单，判断当前时间在21:00-24:00的要默认成次日9:00
        /*if (order.getDutyTime() != null) {
            int time = Integer.parseInt(DateUtil.toString(DateUtil.getNow(), "HHmm"));
            int startTime = 2100;
            int endTime = 2359;

            if (time >= startTime && time <= endTime) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(order.getDutyTime());
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                calendar.set(Calendar.HOUR_OF_DAY, 9);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                order.setDutyTime(calendar.getTime());
            }
        }*/
        // 没有用户名，写死名称为“用户”
        order.setUserName(StringUtils.defaultIfBlank(order.getUserName(),"用户"));
        order.setReceiveEntranceId(GateTypeConsts.GATE_PLAT_CHAT);
        return this.saveNewOrder(order);
    }

    /**
     * 新增普通单
     *
     * @return
     */
    @SuppressWarnings("all")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO saveNormalOrder(@RequestBody @Valid ZsNormalNewOrderDTO order) {
        return this.saveOrder(order);
    }

    /**
     * 新增返修单
     *
     * @return
     */
    @RequestMapping(value = "reworkSave", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO saveReworkOrder(@RequestBody @Valid ZsNormalReworkOrderDTO order) {
        ZsNormalNewOrderDTO normalNewOrderDTO = BeanMapper.map(order, ZsNormalNewOrderDTO.class);

        // 返修原因
        if (CollectionUtil.isNotNullOrEmpty(order.getReworkReasonList())) {
            String reworkReason = String.join("；", order.getReworkReasonList());
            normalNewOrderDTO.setRemark(StringUtils.isNotBlank(order.getRemark())
                    ? String.format("%s；%s", reworkReason, order.getRemark())
                    : String.format("%s", reworkReason));
        }

        return this.saveOrder(normalNewOrderDTO);
    }

    /**
     * 获取下单渠道
     *
     * @param plat
     * @return
     */
    private Integer getAddOrderChannelId(Integer plat) {
        TagsDRO tagsDRO = baseCodeService.getOneBaseCodeMap(plat, TagConsts.TAG_ONE_TYPE_OMS_CHANNEL_TYPE, TagConsts.TAG_TWO_TYPE_OMS_CHANNEL_MASTER);
        Integer channelId = Integer.parseInt(tagsDRO.getName().trim());
        if (NumberUtil.isNullOrZero(channelId)) {
            if (Objects.equals(GlobalConsts.PLAT_MARK_ZMN, plat)) {
                channelId = OrderConsts.CHANNEL_ID_MASTER_RECOMMEND_B;
            } else if (Objects.equals(GlobalConsts.PLAT_MARK_CNHB, plat)) {
                channelId = OrderConsts.CHANNEL_ID_CNHB_MASTER_RECOMMEND;
            }
        }
        return channelId;
    }

    /**
     * 保存工单信息
     *
     * @param order
     * @return
     */
    private ResultDTO saveOrder(ZsNormalNewOrderDTO order) {
        if (Objects.nonNull(order.getCopyOrderId())) {
            logger.info("保存复制订单：copyOrderId={}", order.getCopyOrderId());
            OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(order.getCopyOrderId());
            // 隐藏手机号处理
            if (MobileUtil.isHideTel(order.getTelephone())) {
                order.setTelephone(orderDetail.getTelephone());
            }
            if (MobileUtil.isHideTel(order.getTelephone2())) {
                order.setTelephone2(orderDetail.getTelephone2());
            }
            if (MobileUtil.isHideTel(order.getTelephone3())) {
                order.setTelephone3(orderDetail.getTelephone3());
            }
            // 师傅加单
            /*if (Objects.equals(order.getAddOrder(), com.zmn.consts.GlobalConsts.YES)) {
                order.setOperator(order.getCopyMasterName());
                order.setOperatorId((long) order.getCopyMasterId());
                order.setOperatorType(com.zmn.consts.GlobalConsts.OPERATE_USER_TYPE_MASTER);
                order.setOperatorRemark("后台加单");
                order.setChannelId(this.getAddOrderChannelId(order.getPlat()));
                order.setRecommenderId(order.getOperatorId());
                order.setRecommenderType(com.zmn.consts.GlobalConsts.OPERATE_USER_TYPE_MASTER);
            }*/
        } else if (Objects.nonNull(order.getReworkId())) {
            logger.info("保存返修单：reworkId={}", order.getReworkId());
            OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(order.getReworkId());
            // 隐藏手机号处理
            if (MobileUtil.isHideTel(order.getTelephone())) {
                order.setTelephone(orderDetail.getTelephone());
            }
            if (MobileUtil.isHideTel(order.getTelephone2())) {
                order.setTelephone2(orderDetail.getTelephone2());
            }
            if (MobileUtil.isHideTel(order.getTelephone3())) {
                order.setTelephone3(orderDetail.getTelephone3());
            }
        }

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest httpServletRequest = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String userAgentStr = httpServletRequest.getHeader("User-Agent");

        order.setReceiveEntranceId(NumberUtil.isNullOrZero(order.getReceiveEntranceId()) ? GateTypeConsts.GATE_PLAT_BACKSTAGE : order.getReceiveEntranceId());
        order.setInputType(OrderConsts.ORDER_INPUT_TYPE_MANUAL);
        order.setReceiverManner(OrderConsts.RECEIVE_MANNER_MANUAL);

        logger.debug("新增普通单--：{}", order);

        NormalOrderAddDIO normalOrderAddDIO = BeanMapper.map(order, NormalOrderAddDIO.class);
        normalOrderAddDIO.setOperatorIP(order.getIp());
        normalOrderAddDIO.setUserAgent(userAgentStr);
        // 基础信息
        OrderBaseInfo orderBaseInfo = BeanMapper.map(order, OrderBaseInfo.class);
        normalOrderAddDIO.setOrderBaseInfo(orderBaseInfo);
        // 用户信息
        UserDIO userDIO = BeanMapper.map(order, UserDIO.class);
        userDIO.setContactName(order.getUserName());
        normalOrderAddDIO.setUserDIO(userDIO);
        // 产品信息
        List<OrderProductDIO> orderProductList = Lists.newArrayListWithCapacity(1);
        order.getOrderProductList().forEach(product -> {
            OrderProductDIO orderProductAddDIO = BeanMapper.map(product, OrderProductDIO.class);
            // 后台产品，情况前台
            if (Objects.equals(product.getProductShowType(), BaseProductConsts.ERP_SHOW_TYPE)) {
                orderProductAddDIO.setShowProductId(null);
            } else {
                orderProductAddDIO.setProductId(null);
            }
            orderProductAddDIO.setDutyTime(order.getDutyTime());
            orderProductAddDIO.setServCategId(order.getServCategId());
            orderProductAddDIO.setCategId(order.getCategId());
            orderProductList.add(orderProductAddDIO);
        });
        normalOrderAddDIO.setOrderProductList(orderProductList);

        normalOrderAddDIO.setOrderServiceItemList(this.getServiceItem(order));

        if (zsOrderBService.isHaveSameCancelOrder(userDIO, order.getOrderProductList())) {
            return ResultDTO.fail(ADD_LIMIT_NOTICE);
        }

        logger.info("普通单#normalOrderRemoteService#addOrder入参：[{}]", JSON.toJSONString(normalOrderAddDIO));
        ResponseDTO<OrderAddDRO> responseDTO = normalOrderRemoteService.addOrder(normalOrderAddDIO);
        logger.info("普通单#normalOrderRemoteService#addOrder出参：[{}]", JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess()) {
            return ResultDTO.fail(responseDTO.getMessage());
        }

        OrderAddDRO orderAddDRO = responseDTO.getData();
        AddOrderVO addOrderVO = new AddOrderVO();
        OrderWork orderWork = new OrderWork();
        orderWork.setOrderId(orderAddDRO.getOrderId());
        orderWork.setWorkId(orderAddDRO.getOrderId());
        addOrderVO.setOrderWork(orderWork);
        addOrderVO.setMessage("操作成功");
        // 日志
        return ResultDTO.success(addOrderVO);
    }

    /**
     * 新增普通单
     *
     * @return
     */
    @SuppressWarnings("all")
    @RequestMapping(value = "/shoppingCart/save", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO saveNewOrder(@RequestBody @Valid NewZsNormalNewOrderDTO order) {
        if (!this.simpleOrderCheck(order)) {
            return ResultDTO.fail(ADD_LIMIT_NOTICE);
        }

        order.setReceiveEntranceId(NumberUtil.isNullOrZero(order.getReceiveEntranceId()) ? GateTypeConsts.GATE_PLAT_BACKSTAGE : order.getReceiveEntranceId());
        order.setInputType(OrderConsts.ORDER_INPUT_TYPE_MANUAL);
        order.setReceiverManner(OrderConsts.RECEIVE_MANNER_MANUAL);

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest httpServletRequest = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String userAgentStr = httpServletRequest.getHeader("User-Agent");

        AddOrderVO addOrderVO = new AddOrderVO();
        OrderWork orderWork = new OrderWork();


        logger.info("新增普通单--：{}", order);
        // 多个产品购物车下单，单个产品普通下单
        if (order.getNewOrderProductList().size() > 1){
            OrderAddDIO dio = BeanMapper.map(order, OrderAddDIO.class);
            dio.setOperatorIP(order.getIp());
            dio.setOpenVIP(GlobalConsts.NO);
            dio.setUserAgent(userAgentStr);
            dio.setBuyNow(GlobalConsts.NO);
            dio.setSupportPay(false);
            // 基础信息
            OrderBaseInfo orderBaseInfo = BeanMapper.map(order, OrderBaseInfo.class);
            orderBaseInfo.setPreManageCompanyId(null);
            orderBaseInfo.setPreManageCompanyName(null);
            dio.setOrderBaseInfo(orderBaseInfo);
            // 用户信息
            UserDIO userDIO = BeanMapper.map(order, UserDIO.class);
            userDIO.setContactName(order.getUserName());
            dio.setUserDIO(userDIO);
            // 产品信息
            List<OrderProductAddDIO> orderProductList = Lists.newArrayListWithCapacity(order.getNewOrderProductList().size());
            order.getNewOrderProductList().forEach(product -> {
                OrderProductAddDIO orderProductAddDIO = new OrderProductAddDIO();
                orderProductAddDIO.setDutyTime(product.getDutyTime());
                if (product.getProductId() == 0){
                    orderProductAddDIO.setProductId(product.getShowProductId());
                } else {
                    orderProductAddDIO.setProductId(product.getProductId());
                }
                orderProductAddDIO.setNumber(product.getNumber());
                orderProductAddDIO.setBrandId(product.getBrandId());
                orderProductAddDIO.setFaultIdList(product.getFaultIdList());
                orderProductAddDIO.setRemark(product.getRemark());
                orderProductAddDIO.setTariffId(product.getTariffId());

                if (CollectionUtil.isNotNullOrEmpty(product.getWaitSendDiscountList())) {
                    orderProductAddDIO.setWaitSendDiscountList(BeanMapper.mapList(product.getWaitSendDiscountList(), OrderProductDiscountDIO.class));
                }

                orderProductList.add(orderProductAddDIO);
            });
            dio.setProductList(orderProductList);

            //扩展信息
            ExtraData extraData = BeanMapper.map(order, ExtraData.class);
            dio.setExtraData(extraData);

            // 渠道单号信息
            if (StringUtil.isNotBlank(order.getOuterId())) {
                ChannelApiExtraData channelApiExtraData = new ChannelApiExtraData();
                channelApiExtraData.setOuterId(order.getOuterId());
                dio.setChannelApiExtraData(channelApiExtraData);
            }
            // 外部店铺信息
            if (Objects.nonNull(order.getExternalShopInfo())) {
                ExternalShopDIO externalShopDIO = new ExternalShopDIO();
                externalShopDIO.setExternalShopId(order.getExternalShopInfo().getExternalShopId());
                externalShopDIO.setInternalShopId(order.getExternalShopInfo().getInternalShopId());
                externalShopDIO.setInternalShopName(order.getExternalShopInfo().getInternalShopName());
                externalShopDIO.setInternalBranchShopName(order.getExternalShopInfo().getInternalBranchShopName());
                dio.setExternalShopInfo(externalShopDIO);
            }

            logger.info("购物车#orderModifyRemoteService#addOrder入参：[{}]", JSON.toJSONString(dio));
            ResponseDTO<OrderAddDRO> responseDTO = orderModifyRemoteService.addOrder(dio);
            logger.info("购物车#orderModifyRemoteService#addOrder出参：[{}]", JSON.toJSONString(responseDTO));
            if (!responseDTO.isSuccess()){
                return ResultDTO.fail(responseDTO.getMessage());
            } else {
                OrderAddDRO orderAddDRO = responseDTO.getData();
                orderWork.setOrderId(orderAddDRO.getOrderId());
                orderWork.setWorkId(null);
                // 查询主单详情
                ResponseDTO<OrderDetailDRO> droResponseDTO = orderListRemoteService.findOrderDetailByOrderId(orderWork.getOrderId());
                if (droResponseDTO.isSuccess() && Objects.nonNull(droResponseDTO.getData())){
                    OrderDetailDRO orderDetailDRO = droResponseDTO.getData();
                    orderWork.setUserId(orderDetailDRO.getUserId());
                    orderWork.setChannelId(orderDetailDRO.getChannelId());
                    orderWork.setChannelName(orderDetailDRO.getChannelName());
                    orderWork.setCityId(orderDetailDRO.getCityId());
                    orderWork.setCreateTime(orderDetailDRO.getCreateTime());
                    OrderProductDetailDRO productDetailDRO = orderDetailDRO.getProductList().get(0);
                    orderWork.setDutyTime(productDetailDRO.getDutyTime());

                    OrderDetail orderDetail = new OrderDetail();
                    orderDetail.setDetailId(orderWork.getOrderId());
                    orderDetail.setProvinceId(orderDetailDRO.getProvinceId());
                    orderDetail.setProvinceName(orderDetailDRO.getProvinceName());
                    orderDetail.setCityName(orderDetailDRO.getCityName());
                    orderDetail.setCountyId(order.getCountyId());
                    orderDetail.setCountyName(order.getCountyName());
                    orderDetail.setStreet(orderDetailDRO.getStreet());
                    orderDetail.setAddress(orderDetailDRO.getAddress());
                    orderDetail.setTelephone(orderDetailDRO.getTelephone());
                    orderDetail.setRemark(order.getRemark());

                    // 处理品牌
                    String brandName = null;
                    NewOrderProductDTO productDTO = order.getNewOrderProductList().get(0);
                    if (NumberUtil.isPositiveInteger(productDTO.getBrandId())){
                        ResponseDTO<BrandDRO> responseBrand = brandListRemoteService.getById(productDTO.getBrandId());
                        if (responseBrand.isSuccess() && Objects.nonNull(responseBrand.getData())){
                            brandName = responseBrand.getData().getName();
                        }
                    }

                    orderDetail.setProductInfo(String.format("%s-%s*%s", StringUtils.defaultString(brandName), productDetailDRO.getProductName(), productDetailDRO.getNumber()));
                    addOrderVO.setOrderDetail(orderDetail);
                }
                addOrderVO.setOrderWork(orderWork);
                addOrderVO.setMessage("操作成功");
                return ResultDTO.success(addOrderVO);
            }
        } else {
            NormalOrderAddDIO normalOrderAddDIO = BeanMapper.map(order, NormalOrderAddDIO.class);
            normalOrderAddDIO.setOperatorIP(order.getIp());
            normalOrderAddDIO.setServCategId(order.getNewOrderProductList().get(0).getServCategId());
            normalOrderAddDIO.setUserAgent(userAgentStr);
            // 基础信息
            OrderBaseInfo orderBaseInfo = BeanMapper.map(order, OrderBaseInfo.class);
            normalOrderAddDIO.setOrderBaseInfo(orderBaseInfo);
            // 用户信息
            UserDIO userDIO = BeanMapper.map(order, UserDIO.class);
            userDIO.setContactName(order.getUserName());
            normalOrderAddDIO.setUserDIO(userDIO);
            // 产品信息
            List<OrderProductDIO> orderProductList = Lists.newArrayListWithCapacity(1);
            order.getNewOrderProductList().forEach(product -> {
                OrderProductDIO orderProductAddDIO = BeanMapper.map(product, OrderProductDIO.class);
                orderProductList.add(orderProductAddDIO);
            });
            normalOrderAddDIO.setOrderProductList(orderProductList);

            //扩展信息
            ExtraData extraData = BeanMapper.map(order, ExtraData.class);
            normalOrderAddDIO.setExtraData(extraData);

            // 渠道单号信息
            if (StringUtil.isNotBlank(order.getOuterId())) {
                ChannelApiExtraData channelApiExtraData = new ChannelApiExtraData();
                channelApiExtraData.setOuterId(order.getOuterId());
                normalOrderAddDIO.setChannelApiExtraData(channelApiExtraData);
            }
            // 外部店铺信息
            if (Objects.nonNull(order.getExternalShopInfo())) {
                ExternalShopDIO externalShopDIO = new ExternalShopDIO();
                externalShopDIO.setExternalShopId(order.getExternalShopInfo().getExternalShopId());
                externalShopDIO.setInternalShopId(order.getExternalShopInfo().getInternalShopId());
                externalShopDIO.setInternalShopName(order.getExternalShopInfo().getInternalShopName());
                externalShopDIO.setInternalBranchShopName(order.getExternalShopInfo().getInternalBranchShopName());
                normalOrderAddDIO.setExternalShopInfo(externalShopDIO);
            }

            normalOrderAddDIO.setOrderServiceItemList(this.getServiceItem(order));

            logger.info("普通单#normalOrderRemoteService#addOrder入参：[{}]", JSON.toJSONString(normalOrderAddDIO));
            ResponseDTO<OrderAddDRO> responseDTO = normalOrderRemoteService.addOrder(normalOrderAddDIO);
            logger.info("普通单#normalOrderRemoteService#addOrder出参：[{}]", JSON.toJSONString(responseDTO));
            if (!responseDTO.isSuccess()){
                return ResultDTO.fail(responseDTO.getMessage());
            }
            OrderAddDRO orderAddDRO = responseDTO.getData();
            OrderWork dbOrderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderAddDRO.getOrderId(), orderAddDRO.getOrderId());
            OrderDetail dbOrderDetail = orderDetailService.findOrderDetailByKeySrcMaster(dbOrderWork.getOrderId());
            addOrderVO.setOrderWork(dbOrderWork);
            addOrderVO.setOrderDetail(dbOrderDetail);

            // 如果下单有渠道预付款则插入支付记录
            if (NumberUtil.isNotNullOrZero(order.getChannelPrepayAmount())
                    && StringUtil.isNotBlank(order.getChannelPrepayCertificateSrc())) {
                ZsUpdateChannelPrepayAmountDTO zsUpdateChannelPrepayAmountDTO = new ZsUpdateChannelPrepayAmountDTO();
                zsUpdateChannelPrepayAmountDTO.setOrderId(dbOrderWork.getOrderId());
                zsUpdateChannelPrepayAmountDTO.setWorkId(dbOrderWork.getWorkId());

                zsUpdateChannelPrepayAmountDTO.setChannelPrepayAmount(order.getChannelPrepayAmount());
                zsUpdateChannelPrepayAmountDTO.setChannelPrepayCertificateSrc(order.getChannelPrepayCertificateSrc());
                zsUpdateChannelPrepayAmountDTO.setChannelPrepayAmountDetailList(order.getChannelPrepayAmountDetailList());

                zsUpdateChannelPrepayAmountDTO.setOperator(order.getOperator());
                zsUpdateChannelPrepayAmountDTO.setOperatorId(order.getOperatorId());
                zsUpdateChannelPrepayAmountDTO.setOperatorType(order.getOperatorType());
                zsUpdateChannelPrepayAmountDTO.setOperateTime(DateUtil.getNow());

                zsUpdateChannelPrepayAmountDTO.setIsJudgeOperateAuthority(false);
                zsUpdateChannelPrepayAmountDTO.setOrderWork(dbOrderWork);
                try {
                    zsNormalMasterWorkBService.saveChannelPrepayAmount(zsUpdateChannelPrepayAmountDTO);
                } catch (OmsBaseException e) {
                    logger.error("[{}]该预付款失败：【{}】", dbOrderWork.getOrderId(), e.getMessage());
                    e.printStackTrace();
                    addOrderVO.setMessage("下单成功，预付款录入失败，请前往订单详情页面修改预付款");
                    return ResultDTO.success(addOrderVO);
                }
            }
            addOrderVO.setMessage("操作成功");
            return ResultDTO.success(addOrderVO);
        }

    }

    /**
     * 新增普通单(来源自意向单下单)
     *
     * @return
     */
    @RequestMapping(value = "saveFromPurposeOrder", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO saveFromPurposeOrder(@RequestBody @Valid ZsNormalNewOrderDTO order) {
        try {
            logger.debug("新增普通单：{}", order);
            order.setInputType(OrderConsts.ORDER_INPUT_TYPE_MANUAL);

            //特殊处理
            Integer orderPurposeId = order.getOrderPurposeId();
            orderPurposeBService.updateIsCreateOrder(orderPurposeId);

            return this.saveOrder(order);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.fail(e.getMessage());
        }
    }

    /**
     * 创建普通工单的视图
     *
     * @param viewName 视图名称
     * @return
     */
    private ModelAndView createNormalOrderModelAndView(String viewName, Integer plat) {
        return createNormalOrderModelAndView(viewName, plat, false, null, true);
    }

    /**
     * 创建普通工单的视图
     *
     * @param viewName 视图名称
     * @return
     */
    private ModelAndView createNormalOrderModelAndView(String viewName, Integer plat, boolean allowChannel, ChannelAccessModeEnum accessMode, boolean channelPermit) {
        ModelAndView mav = new ModelAndView(viewName);
        // 性别
        mav.addObject("gender", super.dictModel2KVDict(GlobalDict.getGenderList()));
        // 订单类型
        mav.addObject("type", super.dictModel2KVDict(OrderConsts.getOrderTypeList()));

        if (allowChannel) {
            ChannelListQuery channelListQuery = ChannelListQuery.builder()
                    .plat(plat)
                    .excludeDisabledOrderInput(true)
                    .excludeDisabled(true)
                    .factoryChannel(false)
                    .isPermit(channelPermit).build();
            if (accessMode != null) {
                channelListQuery.setAccessMode(accessMode.getCode());
            }
            mav.addObject("channelList", super.getChannelList(channelListQuery));
            // 省份
            mav.addObject("provinceList", super.getAllProvinceList());
            // 城市ID
            mav.addObject("cityList", super.getAllCityList());
        } else {
            // 需要应用权限
            // 渠道列表 1不禁用，2禁用
            mav.addObject("channelList", super.getChannelListByDept(plat));
            // 省份
            mav.addObject("provinceList", super.getProvinceListByDept());
            // 城市ID
            mav.addObject("cityList", super.getCityListByDept());
        }

        // 服务分类
        mav.addObject("servCategList", super.getShowServCategList());
        // 产品类型
        mav.addObject("productShowType", super.dictModel2KVDict(OrderConsts.getProductShowTypeList()));
        // 品牌
        mav.addObject("brandList", super.getBrandList());

        // 预约失败原因
        mav.addObject("dutyFailReasonList", super.dictModel2KVDict(OrderDutyConsts.getDutyFailReasonList()));
        //物流公司
        mav.addObject("expressCompanyList", super.listExpressCompany());
        // 下单便捷标签
        mav.addObject("commonRemarkList", baseCodeService.listInputRemark());
        // 特殊故障ID
        mav.addObject("specialFaultPhenId", specialFaultPhenId);

        ZsNormalUpdateOrderVO zsNormalUpdateOrderVO = new ZsNormalUpdateOrderVO();
        zsNormalUpdateOrderVO.setBizType(com.zmn.consts.GlobalConsts.BIZ_TYPE_C);
        zsNormalUpdateOrderVO.setPlatWork(plat);
        zsNormalUpdateOrderVO.setPlat(plat);
        zsNormalUpdateOrderVO.setRequestId(IdUtil.simpleUUID());

        mav.addObject("orderInfo", zsNormalUpdateOrderVO);
        return mav;
    }

    @GetMapping("/getRealPhone")
    @ResponseBody
    public ResultDTO getRealPhone(String callId) {
        try {
            logger.info("查询真实号码入参：[{}]", callId);
            ResponseDTO<EncryptDataDRO> reponseDTO = popupListRemoteService.getRealNumByRecordId(callId);
            logger.info("查询真实号码出参：[{}]", reponseDTO);
            if (!reponseDTO.isSuccess() || Objects.isNull(reponseDTO.getData())) {
                return ResultDTO.fail("请填写真实号码");
            }
            if (StringUtil.isBlank(reponseDTO.getData().getCiphertext())) {
                return ResultDTO.fail("请填写真实号码");
            }

            logger.info("手机号解密前：[{}]", reponseDTO.getData().getCiphertext());
            ResponseDTO<String> encryptTelphoneRemote = anoleRemoteService.decrypt(reponseDTO.getData().getCiphertext());
            logger.info("手机号解密后：[{}]", JSON.toJSONString(encryptTelphoneRemote));
            if (!encryptTelphoneRemote.isSuccess() || Objects.isNull(encryptTelphoneRemote.getData())) {
                return ResultDTO.fail("手机号解密失败");
            }

            RealPhoneVO realPhoneVO = new RealPhoneVO();
            realPhoneVO.setRealPhone(encryptTelphoneRemote.getData());
            realPhoneVO.setHidePhone(MobileUtil.formatHideTel(realPhoneVO.getRealPhone()));
            return ResultDTO.success(realPhoneVO);
        } catch (Exception e) {
            return ResultDTO.fail("查询真实手机号异常");
        }
    }

    @GetMapping("/getDecryptPhone")
    @ResponseBody
    public ResultDTO getDecryptPhone(String cryptoPhone) {
        try {
            RealPhoneVO realPhoneVO = new RealPhoneVO();
            ResponseDTO<String> encryptTelphoneRemote = anoleRemoteService.decrypt(cryptoPhone);
            if (!encryptTelphoneRemote.isSuccess() || Objects.isNull(encryptTelphoneRemote.getData())) {
                return ResultDTO.fail("手机号解密失败");
            }
            realPhoneVO.setRealPhone(encryptTelphoneRemote.getData());
            realPhoneVO.setHidePhone(MobileUtil.formatHideTel(realPhoneVO.getRealPhone()));
            return ResultDTO.success(realPhoneVO);
        } catch (Exception e) {
            return ResultDTO.fail("手机号解密失败");
        }
    }

    /**
     * 快捷下单校验
     *
     * @param order
     */
    private boolean simpleOrderCheck(NewZsNormalNewOrderDTO order) {
        UserDIO userDIO = BeanMapper.map(order, UserDIO.class);
        List<OrderProductDTO> orderProductList = BeanMapper.mapList(order.getNewOrderProductList(), OrderProductDTO.class);
        return !zsOrderBService.isHaveSameCancelOrder(userDIO, orderProductList);
    }

    private List<OrderServiceItemDIO> getServiceItem(NewZsNormalNewOrderDTO order) {
        List<OrderServiceItemDIO> serviceItemList = Lists.newArrayList();
        NewOrderProductDTO product = order.getNewOrderProductList().get(0);
        if (Objects.isNull(product.getAdvanceQuote())) {
            return serviceItemList;
        }
        NewOrderAdvanceQuoteDTO advanceQuoteDTO = product.getAdvanceQuote();
        // 查询服务项
        ItemPriceQuery query = ItemPriceQuery
                .builder()
                .productId(product.getProductId())
                .showType(product.getProductShowType())
                .bizType(order.getBizType())
                .brandId(product.getBrandId())
                .channelId(order.getChannelId())
                .cityId(order.getCityId())
                .itemList(Lists.newArrayList(advanceQuoteDTO.getItemId()))
//                .itemStandard(serviceItemQueryDTO.getPriceStandard())
//                .tariffId(serviceItemQueryDTO.getTariffId())
//                .itemTypeId(serviceItemQueryDTO.getItemCategId())
                .build();
        logger.info("itemPriceRemoteService.listItemPriceByQuery itemPriceQuery={}", com.alibaba.fastjson.JSON.toJSONString(query));
        ResponseDTO<List<ItemDRO>> responseDTO = itemPriceRemoteService.listItemPriceByQuery(query);
        logger.info("itemPriceRemoteService.listItemPriceByQuery responseDTO={}", com.alibaba.fastjson.JSON.toJSONString(responseDTO));

        if (!responseDTO.isSuccess()) {
//            throw new OmsBaseException("获取服务项信息失败，请稍后重试");
            logger.info("获取工单服务项失败:{}", responseDTO.getMessage());
            return serviceItemList;
        }
        if (CollectionUtil.isNotNullOrEmpty(responseDTO.getData())) {
            ItemDRO itemDRO = responseDTO.getData().get(0);
            OrderServiceItemDIO orderServiceItemDIO = new OrderServiceItemDIO();
            orderServiceItemDIO.setServItemId(itemDRO.getItemId());
            orderServiceItemDIO.setServItemName(itemDRO.getItemName());
            orderServiceItemDIO.setServItemGroupId(itemDRO.getItemTypeId());
            orderServiceItemDIO.setServItemGroupName(itemDRO.getItemTypeName());
            orderServiceItemDIO.setInternalSettlementPrice(itemDRO.getPriceInternalSettlement());
            orderServiceItemDIO.setExternalSettlementPrice(itemDRO.getPriceExternalSettlement());
            orderServiceItemDIO.setNumber(1);
            orderServiceItemDIO.setItemPrice(itemDRO.getPrice());
            orderServiceItemDIO.setItemUnit(itemDRO.getItemUnit());
            serviceItemList.add(orderServiceItemDIO);
        }
        return serviceItemList;
    }

    private List<OrderServiceItemDIO> getServiceItem(ZsNormalNewOrderDTO order) {
        List<OrderServiceItemDIO> serviceItemList = Lists.newArrayList();
        OrderProductDTO product = order.getOrderProductList().get(0);
        if (Objects.isNull(product.getAdvanceQuote())) {
            return serviceItemList;
        }
        NewOrderAdvanceQuoteDTO advanceQuoteDTO = product.getAdvanceQuote();
        // 查询服务项
        ItemPriceQuery query = ItemPriceQuery
                .builder()
                .productId(product.getProductId())
                .showType(product.getProductShowType())
                .bizType(order.getBizType())
                .brandId(product.getBrandId())
                .channelId(order.getChannelId())
                .cityId(order.getCityId())
                .itemList(Lists.newArrayList(advanceQuoteDTO.getItemId()))
//                .itemStandard(serviceItemQueryDTO.getPriceStandard())
//                .tariffId(serviceItemQueryDTO.getTariffId())
//                .itemTypeId(serviceItemQueryDTO.getItemCategId())
                .build();
        logger.info("itemPriceRemoteService.listItemPriceByQuery itemPriceQuery={}", com.alibaba.fastjson.JSON.toJSONString(query));
        ResponseDTO<List<ItemDRO>> responseDTO = itemPriceRemoteService.listItemPriceByQuery(query);
        logger.info("itemPriceRemoteService.listItemPriceByQuery responseDTO={}", com.alibaba.fastjson.JSON.toJSONString(responseDTO));

        if (!responseDTO.isSuccess()) {
//            throw new OmsBaseException("获取服务项信息失败，请稍后重试");
            logger.info("获取工单服务项失败:{}", responseDTO.getMessage());
            return serviceItemList;
        }
        if (CollectionUtil.isNotNullOrEmpty(responseDTO.getData())) {
            ItemDRO itemDRO = responseDTO.getData().get(0);
            OrderServiceItemDIO orderServiceItemDIO = new OrderServiceItemDIO();
            orderServiceItemDIO.setServItemId(itemDRO.getItemId());
            orderServiceItemDIO.setServItemName(itemDRO.getItemName());
            orderServiceItemDIO.setServItemGroupId(itemDRO.getItemTypeId());
            orderServiceItemDIO.setServItemGroupName(itemDRO.getItemTypeName());
            orderServiceItemDIO.setInternalSettlementPrice(itemDRO.getPriceInternalSettlement());
            orderServiceItemDIO.setExternalSettlementPrice(itemDRO.getPriceExternalSettlement());
            orderServiceItemDIO.setNumber(1);
            orderServiceItemDIO.setItemPrice(itemDRO.getPrice());
            orderServiceItemDIO.setItemUnit(itemDRO.getItemUnit());
            serviceItemList.add(orderServiceItemDIO);
        }
        return serviceItemList;
    }
}
